package api

import (
	"encoding/json"
	"pan/common/conf"
	"pan/common/exception"
	"pan/common/log"
	"pan/common/net"
	"pan/common/util"
)

type DocsRequest struct {
	DocType int `json:"doctype"`
}

type DocsResponse struct {
	FailRsponse

	DocInfos []DocInfo `json:"docinfos"`
}

type DocInfo struct {
	SiteInfo          SiteInfo `json:"SiteInfo"`
	Docid             string   `json:"docid"`
	Name              string   `json:"name"`
	Rev               string   `json:"rev"`
	Size              int64    `json:"size"`
	Duedate           int64    `json:"duedate"`
	CreateTime        int64    `json:"create_time"`
	Creator           string   `json:"creator"`
	Modified          int64    `json:"modified"`
	Editor            string   `json:"editor"`
	Attr              int64    `json:"attr"`
	DocType           int      `json:"doctype"`
	TypeName          string   `json:"typename"`
	DisplayOrder      int64    `json:"displayorder"`
	DownloadWatermark bool     `json:"downloadwatermark"`
}

type SiteInfo struct {
	Id   string `json:"id"`
	Name string `json:"name"`
}

func DocsApi(tokenid string, req *DocsRequest) (*DocsResponse, error) {
	url := util.PathJoin(conf.GlobalConfig.Url, conf.GlobalConfig.Paths.Docs)

	if log.IsDebugEnable() {
		bytes, _ := json.Marshal(req)
		log.Debug("docs post: ", url, ", token:", tokenid, ", body:", string(bytes))
	}

	resp := &DocsResponse{}
	if err := net.PostWithToken(url, tokenid, req, resp); err != nil {
		return nil, err
	}
	if log.IsDebugEnable() {
		result, _ := json.Marshal(resp)
		log.Debug("docs response: ", string(result))
	}
	if resp.Errcode != 0 {
		return nil, exception.NewExpectError("docs failed, %s", resp.FailString())
	}
	return resp, nil
}
